package org.aeon.service.impl;

import io.netty.channel.Channel;
import org.aeon.service.Session;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionMemoryImpl implements Session {
    private final Map<Long, Channel> usernameChannelMap = new ConcurrentHashMap<>();
    private final Map<Channel, Long> channelUsernameMap = new ConcurrentHashMap<>();
    private final Map<Channel, Map<String, Object>> channelAttributesMap = new ConcurrentHashMap<>();// 每个 channel 包含的属性

    @Override
    public void bind(Channel channel, Long userId) {
        usernameChannelMap.put(userId, channel);
        channelUsernameMap.put(channel, userId);
        channelAttributesMap.put(channel, new ConcurrentHashMap<>());
    }

    @Override
    public void unbind(Channel channel) {
        Long userId = channelUsernameMap.remove(channel);
        usernameChannelMap.remove(userId);
        channelAttributesMap.remove(channel);
    }

    @Override
    public Object getAttribute(Channel channel, String name) {
        final Map<String, Object> map = channelAttributesMap.get(channel);
        if (map == null) return null;
        return map.get(name);
    }

    @Override
    public void setAttribute(Channel channel, String name, Object value) {
        channelAttributesMap.get(channel).put(name, value);
    }

    @Override
    public Channel getChannel(Long userId) {
        return usernameChannelMap.get(userId);
    }

    @Override
    public Long getUserId(Channel channel) {
        return channelUsernameMap.get(channel);
    }

    @Override
    public String toString() {
        return usernameChannelMap.toString();
    }
}
